/* 
    处理标签的逻辑
*/
const { sqlQuery } = require('../mysql/index')

const blog = require('./blog')

module.exports = {
    getSignList, getBlogListBySignId, getSignById, getColor
}

//获取所有标签
async function getSignList() {
    let sql = `select * from sign_data;`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, (data) => {
            resolve(data)
        })
    })
}

//获取标签name和其颜色的对应
async function getColor() {
    let sql = `select name,color from sign_data;`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, (data) => {
            resolve(data)
        })
    })
}

//根据id获取标签信息
async function getSignById(id) {
    let sql = `select * from sign_data where id=${id ? id : ''};`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, (data) => {
            resolve(data)
        })
    })
}

//根据标签的id获取该标签对应的博文列表
/*
    思路：先调用blog中的getBlogList方法获取到所有的blog信息，
    从中取出signId值（将其转换为数组形式），遍历并判断是否包含当前id，
    若包含，则将该博文信息添加到返回数组中
 */
async function getBlogListBySignId(id) {
    let result = [];
    return new Promise(function (resolve, reject) {
        blog.getBlogList(-1).then(res => {
            for (let i in res) {
                let signId = res[i].signId;
                if (signId.length == 0) {
                    if (i == res.length - 1) {
                        resolve(result)
                    }
                    continue;
                }
                //标签最多只能放4个，所以这里的逻辑就这么写了。。。。+ 
                if ((signId[0] ? signId[0] : 0) == id) {
                    result.push(res[i])
                }
                if ((signId[1] ? signId[1] : 0) == id) {
                    result.push(res[i])
                }
                if ((signId[2] ? signId[2] : 0) == id) {
                    result.push(res[i])
                }
                if ((signId[3] ? signId[3] : 0) == id) {
                    result.push(res[i])
                }
                if (i == res.length - 1) {
                    resolve(result)
                }
            }
        })
    })
}